﻿$(function () {
    //当页面首次刷新的时候执行的事件 
    if ($("#hSourceType").val() == '1') {
        var trCommon = document.getElementById('trCommon');
        var parentNode = trCommon.parentNode;
        parentNode.removeChild(trCommon);

        $("#Month").combobox({
            editable: false, panelHeight: "auto",
            valueField: "DictionaryName",
            textField: "DictionaryName",
            url: "/Dictionary/GetDictionaryByTypeTag?typeTag=Month",
            onLoadSuccess: function () {
                var data = $("#Month").combobox('getData');
                if (data.length > 0 && $("#hSourceType").val() == '1') {
                    $("#Month").combobox('select', data[0]["DictionaryName"]);
                }
            },
            onSelect: function (record) {
                initBillTable($("#ContractID").combobox('getValue'));
            }
        });

        $("#ContractID").combobox({
            editable: false, panelHeight: "auto",
            valueField: 'ID',
            textField: 'ContractName',
            url: '/ContractInfo/ContractInfoListByProjectIDAndType?projectID=' + $("#hProjectID").val() + '&contractType=' + encodeURI($("#hContractType").val()),
            onLoadSuccess: function () {
                var data = $("#ContractID").combobox('getData');
                if (data.length > 0 && $("#hSourceType").val() == '1') {
                    $("#ContractID").combobox('select', data[0]["ID"]);
                }
            },
            onSelect: function (record) {
                initBillTable(record.ID);
            }
        });
    }
    else {
        initBillTable($("#hContractID").val());
    }

    if ($("#hSourceType").val() == '1' || ($("#hSourceType").val() == '2' && $("#hProcessType").val() == '1' && $("#hHandleState").val() == '0')) {
        var trCommon = document.getElementById('trCommon');
        if (trCommon != null && trCommon != undefined) {
            var parentNode = trCommon.parentNode;
            parentNode.removeChild(trCommon);
        }
        document.getElementById("sectionSalaryDetailsToolBar").style.display = "block"
    }
    else {
        var trRequest = document.getElementById('trRequest');
        var parentNode = trRequest.parentNode;
        parentNode.removeChild(trRequest);

        $('#documentGrid').datagrid({
            url: '/Document/GetDocumentList?instanceID=' + $("#hID").val() + '&Tag=WorkerManagement/SectionSalaryList/Attachment',  //运行期使用
            nowrap: true,
            autoRowHeight: true,
            striped: true,
            collapsible: true,
            rownumbers: true,
            remoteSort: false,
            idField: 'ID',
            singleSelect: true,
            //queryParams: queryData,
            columns: [[
                {
                    title: '文件名', field: 'FileName', width: 200,
                    formatter: function (value, row, index) {
                        return '<a href="' + row["FilePath"] + '">' + value + '</a> ';
                    }
                },
                { title: '文件大小', field: 'FileSize', width: 70, sortable: true },
                { field: 'UploadUserID', hidden: true },
                { title: '上传人', field: 'UploadUser', width: 60, sortable: true },
                { title: '上传时间', field: 'UploadTime', width: 100, sortable: true }

            ]]
        });

    }

    initFlowTable();
});

function initBillTable(contractID) {
    var sourceType = $("#hSourceType").val();
    var processType = $("#hProcessType").val();
    if (sourceType == "1" || (sourceType == "2" && processType == "1" && $("#hHandleState").val() == '0')) {
        $('#sectionSalaryDetailsDataGrid').datagrid({
            url: '/SectionSalary/GetSectionSalaryDetailListForFlow?sourceType=' + $("#hSourceType").val() + '&projectID=' + $("#hProjectID").val() + '&contractType=' + encodeURI($("#hContractType").val()) + '&contractID=' + contractID + '&sectionSalaryID=' + $("#hID").val(),
            iconCls: 'icon-bricks',
            nowrap: true,//当数据长度超出列宽时将会自动截取
            autoRowHeight: false,
            striped: true,//设置为true将交替显示行背景
            collapsible: true,
            pagination: true,
            pageSize: 20,
            remoteSort: false,
            idField: 'ID',//表明该列是一个唯一列。
            singleSelect: true,
            fitColumns: true,
            toolbar: '#sectionSalaryDetailsToolBar',
            columns:
            [[
                { title: 'ID', field: 'ID', hidden: true },
                { title: '身份证', field: 'CertificateNo', align: 'center', width: 100, editor: 'text' },
                { title: '姓名', field: 'Name', align: 'center', width: 100, editor: 'text' },
                { title: '性别', field: 'Sex', align: 'center', width: 50, editor: 'text' },
                { title: '年龄', field: 'Age', align: 'center', width: 50, editor: 'numberbox' },
                { title: '工种', field: 'WorkType', align: 'center', width: 200, editor: 'text' },
                { title: '累计工资发放', field: 'MonthSalary', align: 'center', width: 100, editor: { type: 'numberbox', options: { precision: 2 } } },
                {
                    title: '身份证附件', field: 'IDCAttachment', width: 80, align: 'center',
                    formatter: function (value, row, index) {
                        return "<a href='javascript:void(0)' class='easyui-linkbutton' onclick='$.Upload(\"" + row.ID + "\", \"WorkerManagement/SectionSalaryList/IDCAttachment\")' data-options='plain:true,iconCls:\"icon-blue_lego\"'>附件操作</a>";
                    }
                },
                {
                    title: '合同附件', field: 'ContractAttachment', width: 80, align: 'center',
                    formatter: function (value, row, index) {
                        return "<a href='javascript:void(0)' class='easyui-linkbutton' onclick='$.Upload(\"" + row.ID + "\", \"WorkerManagement/SectionSalaryList/ContractAttachment\")' data-options='plain:true,iconCls:\"icon-blue_lego\"'>附件操作</a>";
                    }
                }
            ]],
            onLoadSuccess: function (data) {
                var billList = data.rows;
                for (var i = 0; i < billList.length; i++) {
                    AddEvent(i);
                }
            }
        });
    }
    else {
        $('#sectionSalaryDetailsDataGrid').datagrid({
            url: '/SectionSalary/GetSectionSalaryDetailListForFlow?sourceType=' + $("#hSourceType").val() + '&projectID=' + $("#hProjectID").val() + '&contractType=' + encodeURI($("#hContractType").val()) + '&contractID=' + contractID + '&sectionSalaryID=' + $("#hID").val(),
            iconCls: 'icon-bricks',
            nowrap: true,//当数据长度超出列宽时将会自动截取
            autoRowHeight: false,
            striped: true,//设置为true将交替显示行背景
            collapsible: true,
            pagination: true,
            pageSize: 20,
            remoteSort: false,
            idField: 'ID',//表明该列是一个唯一列。
            singleSelect: true,
            fitColumns: true,
            columns:
            [[
                { title: 'ID', field: 'ID', hidden: true },
                { title: '身份证', field: 'CertificateNo', align: 'center', width: 100 },
                { title: '姓名', field: 'Name', align: 'center', width: 100 },
                { title: '性别', field: 'Sex', align: 'center', width: 50 },
                { title: '年龄', field: 'Age', align: 'center', width: 50 },
                { title: '工种', field: 'WorkType', align: 'center', width: 200 },
                { title: '累计工资发放', field: 'MonthSalary', align: 'center', width: 100 },
                { title: '身份证附件', field: 'IDCAttachment', align: 'center', width: 150 },
                { title: '合同附件', field: 'ContractAttachment', align: 'center', width: 150 }
            ]]
        });
    }
}

function initFlowTable() {
    var id = $("#hID").val();
    $('#myDataGrid').datagrid({
        url: '/ProcessedTask/ProcessedTaskList?recordID=' + id,
        fitColumns: true,
        nowrap: true,
        autoRowHeight: false,
        striped: true,
        collapsible: true,
        pagination: true,
        pageSize: 20,
        rownumbers: true,
        remoteSort: false,
        idField: 'ID',
        singleSelect: true,
        columns: [[
                    { title: '节点名称', field: 'CurrentProcessNodeName', width: 200, sortable: true },
                    { title: '审批意见', field: 'ApprovalOpinion', width: 300, sortable: true },
                    { title: '处理人部门', field: 'CurrentProcessPersonDepartmentName', width: 100, sortable: true },
                    { title: '处理人', field: 'CurrentProcessPersonName', width: 100, sortable: true },
                    { title: '处理时间', field: 'ProcessTimeFormat', width: 100, sortable: true }
        ]]
    });

    $('#myCirculatedDataGrid').datagrid({
        url: '/FlowProcessMessage/GetFlowProcessMessageListForReceipt?recordID=' + id + "&processType=1",
        iconCls: 'icon-bricks',
        nowrap: true,
        autoRowHeight: false,
        striped: true,
        collapsible: true,
        pagination: true,
        pageSize: 20,
        remoteSort: false,
        idField: 'ID',
        singleSelect: true,
        columns: [[
                    { title: '描述', field: 'DisplayText', width: 600, sortable: true },
                    { title: '时间', field: 'AssociatedDate', width: 200, sortable: true }
        ]]
    });

    $('#myReceiptDataGrid').datagrid({
        url: '/FlowProcessMessage/GetFlowProcessMessageListForReceipt?recordID=' + id + "&processType=2",
        iconCls: 'icon-bricks',
        nowrap: true,
        autoRowHeight: false,
        striped: true,
        collapsible: true,
        pagination: true,
        pageSize: 20,
        remoteSort: false,
        idField: 'ID',
        singleSelect: true,
        columns: [[
                    { title: '描述', field: 'DisplayText', width: 600, sortable: true },
                    { title: '时间', field: 'AssociatedDate', width: 200, sortable: true }
        ]]
    });
}

function AddEvent(currentIndex) {
    $('#sectionSalaryDetailsDataGrid').datagrid('beginEdit', currentIndex);
    var editorCertificateNo = $('#sectionSalaryDetailsDataGrid').datagrid('getEditor', { index: currentIndex, field: 'CertificateNo' });
    var editorName = $('#sectionSalaryDetailsDataGrid').datagrid('getEditor', { index: currentIndex, field: 'Name' });
    var editorSex = $('#sectionSalaryDetailsDataGrid').datagrid('getEditor', { index: currentIndex, field: 'Sex' });
    var editorAge = $('#sectionSalaryDetailsDataGrid').datagrid('getEditor', { index: currentIndex, field: 'Age' });
    var editorWorkType = $('#sectionSalaryDetailsDataGrid').datagrid('getEditor', { index: currentIndex, field: 'WorkType' });
    var editorMonthSalary = $('#sectionSalaryDetailsDataGrid').datagrid('getEditor', { index: currentIndex, field: 'MonthSalary' });

    editorCertificateNo.target.bind('click', function () {
        var tr = $(this).closest('tr.datagrid-row');
        var index = parseInt(tr.attr('datagrid-row-index'));
        $('#sectionSalaryDetailsDataGrid').datagrid('selectRow', index);
    });

    editorName.target.bind('click', function () {
        var tr = $(this).closest('tr.datagrid-row');
        var index = parseInt(tr.attr('datagrid-row-index'));
        $('#sectionSalaryDetailsDataGrid').datagrid('selectRow', index);
    });

    editorSex.target.bind('click', function () {
        var tr = $(this).closest('tr.datagrid-row');
        var index = parseInt(tr.attr('datagrid-row-index'));
        $('#sectionSalaryDetailsDataGrid').datagrid('selectRow', index);
    });

    editorAge.target.bind('click', function () {
        var tr = $(this).closest('tr.datagrid-row');
        var index = parseInt(tr.attr('datagrid-row-index'));
        $('#sectionSalaryDetailsDataGrid').datagrid('selectRow', index);
    });

    editorWorkType.target.bind('click', function () {
        var tr = $(this).closest('tr.datagrid-row');
        var index = parseInt(tr.attr('datagrid-row-index'));
        $('#sectionSalaryDetailsDataGrid').datagrid('selectRow', index);
    });

    editorMonthSalary.target.bind('click', function () {
        var tr = $(this).closest('tr.datagrid-row');
        var index = parseInt(tr.attr('datagrid-row-index'));
        $('#sectionSalaryDetailsDataGrid').datagrid('selectRow', index);
    });
}

var SectionSalary =
    {
        Save: function () {
            $('#sectionSalaryDetailsDataGrid').datagrid('acceptChanges');
            var sectionSalaryDetailList = $('#sectionSalaryDetailsDataGrid').datagrid('getData').rows;
            var sectionSalaryDetailListJson = JSON.stringify(sectionSalaryDetailList);
            $('#hSectionSalaryDetailListJson').val(sectionSalaryDetailListJson);
            $('#frmSectionSalary').form('submit', {
                url: '/SectionSalary/Save',
                onSubmit: function () {

                },
                success: function (data) {
                    if (data != "保存成功！") {
                        $.EasyuiSlide(data);
                    }
                    else {
                        if ($("#hSourceType").val() == '1') {
                            $('#ContractID').combobox('disable');
                            $('#Month').combobox('disable');
                        }
                        $('#btnCirculation').linkbutton('enable');
                        $('#btnCirculated').linkbutton('enable');
                        $.EasyuiSlide(data);
                    }
                    for (var i = 0; i < sectionSalaryDetailList.length; i++) {
                        AddEvent(i);
                    }
                },
                fail: function (data) {
                    $.EasyuiSlide(data);
                }
            });
        },

        Circulation: function () {
            var flowCode = $("#hFlowCode").val();
            var id = $("#hID").val();
            var handleState = $("#hHandleState").val();
            var nodeCode = $("#hAssociatedNodeCode").val();
            var processUserDepartment = $("#hLastUpdateUserDepartment").val();
            var processUser = $("#hLastUpdateUser").val();

            showMyWindow("#sectionSalaryWindow", "流程审批", "/Flow/CirculationFlow?flowCode=" + flowCode + "&recordID=" + id + "&handleState=" + handleState + "&currentFlowNodeCode=" + nodeCode + "&processUserDepartment=" + processUserDepartment + "&processUser=" + processUser, 500, 250, true, false);
        },

        Withdraw: function () {
            var withdrawNodeCode = $("#hProcessdOrCirculatedNodeCode").val();
            $('#frmSectionSalary').form('submit', {
                url: '/SectionSalary/Withdraw?withdrawNodeCode=' + withdrawNodeCode,
                onSubmit: function () {

                },
                success: function (data) {
                    window.parent.CloseWindow('撤回成功！');
                },
                fail: function (data) {
                    $.EasyuiSlide(data);
                }
            });
        },

        Back: function () {
            var flowCode = $("#hFlowCode").val();
            var id = $("#hID").val();
            var nodeCode = $("#hAssociatedNodeCode").val();
            showMyWindow("#sectionSalaryWindow", "流程回退", "/Flow/BackFlow?flowCode=" + flowCode + "&recordID=" + id + "&flowNodeCode=" + nodeCode, 550, 400, true, false);
        },

        Cancel: function () {
            var flowCode = $("#hFlowCode").val();
            var id = $("#hID").val();
            $.post("/SectionSalary/Cancel?flowCode=" + flowCode + "&id=" + id, function (res) {
                if (res == "Success") {
                    window.parent.CloseWindow('终止成功！');
                }
                else {
                    $.EasyuiSlide(res);
                }
            });
        },

        Circulated: function () {
            var flowCode = $("#hFlowCode").val();
            var id = $("#hID").val();
            var nodeCode = $("#hProcessdOrCirculatedNodeCode").val();
            var department = $("#hProcessdOrCirculatedUserDepartment").val();
            showMyWindow("#sectionSalaryWindow", "流程传阅", "/Flow/CirculatedFlow?flowCode=" + flowCode + "&recordID=" + id + "&nodeCode=" + nodeCode + "&department=" + department, 400, 400, true, false);
        },

        Receipt: function () {
            var flowCode = $("#hFlowCode").val();
            var messageID = $("#hSourceID").val();
            showMyWindow("#sectionSalaryWindow", "流程已阅", "/Flow/ReceiptFlow?flowCode=" + flowCode + "&messageID=" + messageID, 500, 250, true, false);
        },

        Reminders: function () {
            var flowCode = $("#hFlowCode").val();
            var id = $("#hID").val();
            $.post("/SectionSalary/Reminders?flowCode=" + flowCode + "&id=" + id, function (res) {
                if (res == "Success") {
                    window.parent.CloseWindow('催办成功！');
                }
                else {
                    $.EasyuiSlide(res);
                }
            });
        },

        AddDetails: function () {
            var sectionSalaryDetailList = $('#sectionSalaryDetailsDataGrid').datagrid('getData').rows;
            $('#sectionSalaryDetailsDataGrid').datagrid('insertRow', {
                index: sectionSalaryDetailList.length,
                row: {
                    ID: NewGuid(),
                    CertificateNo: '',
                    Name: '',
                    Sex: '男',
                    Age: '',
                    WorkType: '',
                    MonthSalary: 0
                }
            });
            sectionSalaryDetailList = $('#sectionSalaryDetailsDataGrid').datagrid('getData').rows;
            for (var i = 0; i < sectionSalaryDetailList.length; i++) {
                $('#sectionSalaryDetailsDataGrid').datagrid('beginEdit', i);
            }
        },

        DeleteDetails: function () {
            var row = $("#sectionSalaryDetailsDataGrid").datagrid("getSelected");
            if (row) {
                $.messager.confirm('操作提示', "确认删除农民工【" + row.Name + "】的工资信息吗？", function (r) {
                    if (r) {
                        var index = $("#sectionSalaryDetailsDataGrid").datagrid("getRowIndex", row);
                        $('#sectionSalaryDetailsDataGrid').datagrid('deleteRow', index);
                    }
                });
            }
            else {
                $.messager.alert('操作提示', "请选择要删除的农民工工资信息", 'info');
            }
        }
    }

function CloseSelf() {
    var handleState = $("#hHandleState").val();
    window.parent.cancelPopWindow(handleState);
}

function PreviewProcessGraph(title, index) {
    if (index == 1) {
        var flowCode = $("#hFlowCode").val();
        var id = $("#hID").val();
        $.post("/SectionSalary/GenerateGraph?flowCode=" + flowCode + "&id=" + id, function (res) {
            var container = document.getElementById('graphContainer');
            if (container.hasChildNodes()) {
                $("#graphContainer").empty()
            }
            PreviewGraph(container, res);
        }
        )
    }
}

//关闭弹出窗口，按条件刷新主界面
//0：取消，1：发送，2：回退，3：传阅，4：已阅
function CloseWindow(closeType, data) {
    colseMyWindow("#sectionSalaryWindow");
    if (closeType != 0) {
        window.parent.CloseWindow(data);
    }
}

function cancelPopWindow() {
    colseMyWindow("#sectionSalaryWindow");
}
